package com.youmingxing.activity.selfInfo;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tencent.upload.task.ITask;
import com.tencent.upload.task.IUploadTaskListener;
import com.tencent.upload.task.data.FileInfo;
import com.youmingxing.R;
import com.youmingxing.activity.BaseActivity;
import com.youmingxing.activity.WorksCommitGuideActivity;
import com.youmingxing.adpter.ContentListAdapter;
import com.youmingxing.adpter.PersonalInfoAuditionAdapter;
import com.youmingxing.adpter.RecyclerViewAdapter.PersonalFansAdapter;
import com.youmingxing.bean.AuditionFromUser;
import com.youmingxing.bean.Content;
import com.youmingxing.bean.User;
import com.youmingxing.bean.selfinfo.FansOrFocus;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.dialog.ShareDialog;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.network.TXYUploadManager;
import com.youmingxing.utils.DisplayUtil;
import com.youmingxing.utils.LogUtil;
import com.youmingxing.utils.Util;
import com.youmingxing.view.DialogManager;
import com.youmingxing.view.ExpandableTextView;
import com.youmingxing.view.RefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * @since 2015-9-22
 * 艺人档案
 */

public class PersonalInfoActivity extends BaseActivity implements View.OnClickListener, RefreshListView.OnLoadMoreListener {
    View headerView;
    //个人信息
    private ImageView userImage;
    private ImageView identityImage;
    ;
    private ImageView userBg;
    private TextView userName;
    private TextView userSchool;
    private ExpandableTextView expandableTextView;
    private String[] userData; //用户信息
    private int userId; //用户信息
    private User user; //用户信息
    private String url;//上传的图片url
    //私信关注
    private LinearLayout attentionLl;
    private TextView focusTv;
    private LinearLayout messageLl;
    //粉丝
    private List<FansOrFocus> fansList;
    private TextView fans_num;
    private TextView fans_num_more;
    private RecyclerView horizontalView;

    //活动
    private RefreshListView auditionList;
    private TextView auditionNum;
    private PersonalInfoAuditionAdapter auditionAdapter;

    //作品
    private List<Content> contentList;
    private ContentListAdapter adapter;
    private RefreshListView listView;
    private TextView contentNum;
    private int mark = 1;//页码信息

    private static final int BACKGROUND_IMAGE = 1;
    private static final int EDIT_INFO = 2;

    public static final String EXTRAS_ID = "u_id";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_personinfo);
        setTopbarName(R.string.title_activity_profile);
        DialogManager.showDialog(this, "加载中");
        userId = getIntent().getExtras().getInt(EXTRAS_ID);
        contentList = new ArrayList<>();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取该用户的个人信息
        AllStarApi.getUserProfile(userId, infoHandler);
    }

    private void initView() {
        setLeftAndrightTv(true, true, true, -1, null, null, this);
        rightImage.setImageResource(R.mipmap.share_btn);
        listView = (RefreshListView) findViewById(R.id.personal_listview);
        listView.setOnLoadMoreListener(this);
        if (headerView == null) { //第一次加载
            headerView = getLayoutInflater().inflate(R.layout.activity_personinfo_top, null);
            listView.addHeaderView(headerView);
        }

        //个人信息
        userImage = (ImageView) headerView.findViewById(R.id.user_icon);
        identityImage = (ImageView) headerView.findViewById(R.id.authentication_img);

        userName = (TextView) headerView.findViewById(R.id.user_name);
        userSchool = (TextView) headerView.findViewById(R.id.user_area);
        userBg = (ImageView) headerView.findViewById(R.id.user_bg);

        //私信关注
        attentionLl = (LinearLayout) headerView.findViewById(R.id.attention_ll);
        focusTv = (TextView) headerView.findViewById(R.id.focus_tv);
        attentionLl.setOnClickListener(this);
        messageLl = (LinearLayout) headerView.findViewById(R.id.message_ll);
        attentionLl.setOnClickListener(this);
        messageLl.setOnClickListener(this);

        expandableTextView = (ExpandableTextView) headerView.findViewById(R.id.expand_text_view);
        //粉丝
        fansList = new ArrayList<>();
        horizontalView = (RecyclerView) headerView.findViewById(R.id.recyclerview_horizontal);
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        horizontalView.setLayoutManager(linearLayoutManager);
        fans_num_more = (TextView) headerView.findViewById(R.id.fans_num_more);
        fans_num = (TextView) headerView.findViewById(R.id.fans_num);
        fans_num_more.setOnClickListener(this);
        //活动
        auditionList = (RefreshListView) headerView.findViewById(R.id.user_audition_list);
        //????
        //auditionList.setFootVisible(false);
        auditionAdapter = new PersonalInfoAuditionAdapter(this);
        auditionAdapter.userId = userId;
        auditionList.setAdapter(auditionAdapter);
        auditionNum = (TextView) headerView.findViewById(R.id.myauditions);
        //作品
        contentNum = (TextView) headerView.findViewById(R.id.dynamic_num);
        adapter = new ContentListAdapter(this);
        listView.setAdapter(adapter);
    }

    //更新用户信息相关视图
    private void updateUserInfo() {
        if (userId == GlobalDataManager.userId) {
            //我的主页
            headerView.findViewById(R.id.edit_ll).setOnClickListener(this);
            headerView.findViewById(R.id.edit_image).setVisibility(View.VISIBLE);
            userBg.setOnClickListener(this);
            findViewById(R.id.edit_image).setVisibility(View.VISIBLE);
            findViewById(R.id.dynamic_img).setVisibility(View.VISIBLE);
            findViewById(R.id.dynamic_img).setOnClickListener(this);
            fans_num.setText("我的金牌粉丝(" + user.fans_num + "人)");
            auditionNum.setText("我的活动项目");
            contentNum.setText("我的作品(" + user.update_count + "条)");
            Glide.with(getApplicationContext()).load(userData[User.Info.background_img.ordinal()])
                    .placeholder(R.mipmap.bg_mine).error(R.mipmap.bg_mine)
                    .animate(R.anim.abc_fade_in).into(userBg);
        } else {
            contentNum.setText("TA的作品(" + user.update_count + "条)");
            fans_num.setText("TA的金牌粉丝(" + user.fans_num + "人)");
            auditionNum.setText("TA的活动项目");
            Glide.with(getApplicationContext()).load(userData[User.Info.background_img.ordinal()])
                    .placeholder(R.mipmap.bg_others).error(R.mipmap.bg_others)
                    .animate(R.anim.abc_fade_in).into(userBg);
        }
        setFocusStyle();
        //设置人气值
        ((TextView) findViewById(R.id.popularity_value_tv)).setText(user.popularity + "");
        View indicator = findViewById(R.id.popularity_value);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) indicator.getLayoutParams(); //取控件textView当前的布局参数
        params.height = (int) (DisplayUtil.dip2px(260) * user.popularityRatio);// 控件的高强制设成20
        //设置个人信息
        Glide.with(getApplicationContext()).load(userData[User.Info.headimg.ordinal()])
                .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar)
                .bitmapTransform(new CropCircleTransformation(this)).crossFade().into(userImage);

        userName.setText(userData[User.Info.nickname.ordinal()]);

        LogUtil.i("--------personInfo---", "-url--" + AllStarApi.getUserMarkIcon
                (Integer.parseInt(user.user_type)));
        Glide.with(getApplicationContext()).load(AllStarApi.getUserMarkIcon
                (Integer.parseInt(user.user_type))).
                crossFade().into(identityImage);

        userSchool.setText(Util.generateInfo(userData));
        if (userData[User.Info.motto.ordinal()].isEmpty()) {
            findViewById(R.id.ll_motto).setVisibility(View.GONE);
        } else {
            expandableTextView.setText(userData[User.Info.motto.ordinal()]);
            findViewById(R.id.ll_motto).setVisibility(View.VISIBLE);
        }
        TextView userShapeTv = (TextView) findViewById(R.id.user_shape);
        userShapeTv.setText(user.shapeInfo);
    }

    private void setFocusStyle() {
        if (user.myfollow) {
            attentionLl.setBackgroundResource(R.drawable.btn_red_edge_radius5);
            focusTv.setText("已关注");
            focusTv.setTextColor(getResources().getColor(R.color.rgb245_75_75));
            Drawable like = getResources().getDrawable(R.mipmap.right);
            focusTv.setCompoundDrawablesWithIntrinsicBounds(like, null, null, null);
        } else {
            attentionLl.setBackgroundResource(R.drawable.btn_redbg);
            focusTv.setText("关注TA");
            focusTv.setTextColor(getResources().getColor(R.color.whitefd));
            Drawable like = getResources().getDrawable(R.mipmap.eye);
            focusTv.setCompoundDrawablesWithIntrinsicBounds(like, null, null, null);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.header_iv_right:
                showShareDialog();
                break;
            case R.id.edit_ll:
                Intent intent = new Intent(PersonalInfoActivity.this, ModifyInfoActivity.class);
                intent.putExtra("userData", userData);
                startActivityForResult(intent, EDIT_INFO);
                break;
            case R.id.message_ll:
//                SelfInfoApi.isCansendMessage(new BaseJsonHandler(this) {
//                    @Override
//                    public void onSuccessWithData(JSONObject response) {
//                        LogUtil.i("------isCansendMessage--","" + response);
//                        int result = response.optJSONObject("data").optInt("result");
//                        if (result == 1) {
//                            if (user.myfollow) {
//                                user.myfollow = false;
//                            } else {
//                                user.myfollow = true;
//                            }
//                            setFocusStyle();
//                            SelfInfoApi.getUserFans(0, userId, fansHandler);
//                        }
//                    }
//                });
                showToast("私信功能即将开放，敬请期待哦！");
                if (true) { //   人气值不足
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("popularNum", 100);
////                    MessageReportDialog dialog = new MessageReportDialog();
////                    dialog.setArguments(bundle);
////                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
////                    dialog.show(ft, "PersonalMessageDialog");
//
//                    PersonalMessageDialog dialog = new PersonalMessageDialog();
//                    dialog.setArguments(bundle);
//                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//                    dialog.show(ft, "PersonalMessageDialog");


                } else {

                }
//                showToast("私信功能即将开放，敬请期待哦！");
                break;
            case R.id.attention_ll:
                if (GlobalDataManager.userId == userId) {
                    showToast("您不能关注自己哦");
                    return;
                }
                showDialog("正在提交");
                int operate = 0;
                if (!user.myfollow) {
                    operate = 1;
                }
                AllStarApi.focus(user.id, operate, new
                        BaseJsonHandler
                                (this) {
                            @Override
                            public void onSuccessWithData(JSONObject response) {
                                int result = response.optJSONObject("data").optInt("result");
                                if (result == 1) {
                                    if (user.myfollow) {
                                        user.myfollow = false;
                                    } else {
                                        user.myfollow = true;
                                    }
                                    setFocusStyle();
                                    SelfInfoApi.getUserFans(0, userId, fansHandler);
                                }
                            }
                        });
                break;
            case R.id.fans_num_more:
                Intent intentFan = new Intent(PersonalInfoActivity.this, FansActivity.class);
                intentFan.putExtra(FansActivity.EXTRAS_ID, user.id);
                startActivity(intentFan);
                break;
            case R.id.audition_more:
                Intent intentAudition = new Intent(PersonalInfoActivity.this, MyAllAuditionsActivity.class);
                intentAudition.putExtra(MyAllAuditionsActivity.EXTRAS_USER_ID, user.id);
                startActivity(intentAudition);
                break;
            case R.id.dynamic_img:
                showNewWorkDialog();
                break;
            case R.id.user_bg:
                PhotoPickerIntent intentPP = new PhotoPickerIntent(PersonalInfoActivity.this);
                intentPP.setPhotoCount(1);
                intentPP.setShowCamera(true);
                intentPP.setShowGif(false);
                startActivityForResult(intentPP, BACKGROUND_IMAGE);
                break;
            default:
                break;
        }
    }


    private void showShareDialog() {
        Intent intent = new Intent(PersonalInfoActivity.this, ShareDialog.class);
        intent.putExtra("id", user.id);
        intent.putExtra("entrance", 1);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == EDIT_INFO) {
            if (resultCode == RESULT_OK) {
                userData = data.getStringArrayExtra("userData");
                updateUserInfo();
            }
        }
        if (requestCode == BACKGROUND_IMAGE) {
            if (resultCode == RESULT_OK) {
                String photoPath = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS).get(0);
                uploadPic(photoPath);
            }
        }
    }

    @Override
    public void onErrorClick() {
        AllStarApi.getUserProfile(userId, infoHandler);
    }


    //个人信息handler
    private BaseJsonHandler infoHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            showErrorPage(false);
            if (headerView == null) {
                initView();
            }
            JSONObject data = response.optJSONObject("data");
            user = new User(data);
            userData = user.getUserData();
            updateUserInfo();
            //获取该用户的作品
            if (mark == 1) {
                contentList = new ArrayList<>();
                AllStarApi.getUserContents(userId, mark, contentJsonHandler);
            }
            //获取该用户的粉丝
            if (fansList.size() == 0) {
                SelfInfoApi.getUserFans(0, userId, fansHandler);
            }
            //获取该用户的活动
            AllStarApi.getUserAudition(userId, -1, auditionHandler);
        }

        @Override
        public void onFail(int statusCode, String statusText) {
            super.onFail(statusCode, statusText);
            showErrorPage(true);
        }
    };

    //作品handler
    private BaseJsonHandler contentJsonHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            listView.endLoadMore();
            JSONArray data = response.optJSONArray("data");
            if (data.length() == 0) {
                if (mark == 1) {
                    listView.noData("还没有作品哦");
                } else {
                    listView.noMoreData();
                }
            }
            for (int i = 0; i < data.length(); i++) {
                Content thisContent = new Content(data.optJSONObject(i));
                if (userId == GlobalDataManager.userId) {
                    thisContent.isShowDelete = true;
                }
                thisContent.u_apply_id = -1;
                contentList.add(thisContent);
            }
            adapter.setData(contentList);
            mark++;
        }
    };

    //更换背景handler
    private BaseJsonHandler editBgHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            DialogManager.dismissDialog();
            if (response.optJSONObject("data").optInt("result") == 1) {
                userData[User.Info.background_img.ordinal()] = url;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        updateUserInfo();
                        showToast("修改成功");
                    }
                });
            } else {
                showToast("修改失败");
            }
        }
    };

    //粉丝handler
    private BaseJsonHandler fansHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            JSONArray data = response.optJSONArray("data");
            if (data.length() == 0) {
                findViewById(R.id.fans_more_layout).setVisibility(View.GONE);
            } else {
                findViewById(R.id.fans_more_layout).setVisibility(View.VISIBLE);
                View more = findViewById(R.id.fans_num_more);
                if (data.length() < 20) {
                    //不显示更多
                    more.setVisibility(View.INVISIBLE);
                } else {
                    more.setVisibility(View.VISIBLE);
                    more.setOnClickListener(PersonalInfoActivity.this);
                }
            }
            fansList.clear();//清空
            for (int i = 0; i < data.length(); i++) {
                FansOrFocus bean = new FansOrFocus(data.optJSONObject(i));
                fansList.add(bean);
            }
            //设置适配器
            PersonalFansAdapter mAdapter = new PersonalFansAdapter(PersonalInfoActivity.this,
                    fansList);
            horizontalView.setAdapter(mAdapter);
            mAdapter.setOnItemClickLitener(new PersonalFansAdapter.OnItemClickLitener() {
                @Override
                public void onItemClick(View view, int position) {
                    Intent intent = new Intent(PersonalInfoActivity.this, PersonalInfoActivity.class);
                    intent.putExtra(PersonalInfoActivity.EXTRAS_ID, fansList.get(position).id);
                    startActivity(intent);
                }
            });
        }
    };

    //活动handler
    private BaseJsonHandler auditionHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            JSONArray data = response.optJSONArray("data");
            if (data.length() == 0) {
                //没有活动
                auditionList.noData("还没有参加活动哟");
            } else {
                if (data.length() > 1) {
                    findViewById(R.id.audition_more).setVisibility(View.VISIBLE);
                    findViewById(R.id.audition_more).setOnClickListener(PersonalInfoActivity.this);
                } else {
                    findViewById(R.id.audition_more).setVisibility(View.GONE);
                }
                List<AuditionFromUser> list = new ArrayList<>();
                AuditionFromUser audition = new AuditionFromUser(data.optJSONObject(0));
                list.add(audition);
                auditionAdapter.setData(list);
            }
        }
    };


    android.os.Handler handler = new android.os.Handler();

    public void uploadPic(String photoPath) {
        DialogManager.showDialog(this, "上传图片中");
        //修改背景图片回调
        TXYUploadManager.uploadPhoto(photoPath, new IUploadTaskListener() {
                    @Override
                    public void onUploadSucceed(final FileInfo fileInfo) {
                        url = fileInfo.url;
                        SelfInfoApi.modifyUserProfile("background_img", fileInfo.url, editBgHandler);
                    }

                    @Override
                    public void onUploadFailed(int i, String s) {
                    }

                    @Override
                    public void onUploadProgress(long l, long l1) {
                    }

                    @Override
                    public void onUploadStateChange(ITask.TaskState taskState) {
                    }
                }
        );
    }

    private void showNewWorkDialog() {
        Intent intent = new Intent(this, WorksCommitGuideActivity.class);
        startActivity(intent);

    }

    @Override
    public void onLoadMore() {
        AllStarApi.getUserContents(userId, mark, contentJsonHandler);
    }
}
